/**
 * @description 产品管理
 * @author
 */

import React, { PropTypes, PureComponent, Fragment } from 'react';
import { NoQueryC, TableC, PrimaryC, ModalC, InputNumberC } from '../../../../comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message, Table, Modal } from 'antd';
import { connect } from 'dva';
import 'moment/locale/zh-cn';
import MyModal from '../common/myModal';
import style from '../index.less';
@Form.create()
@connect(({ ProductManageM, loading }) => ({
  ProductManageM,
  loading: loading.effects['ProductManageM/getTableData'],
}))
export default class ProductManage extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      search: null,
      isVisible: false,
      id: '',
      record: {},
      currentPage: 1,
      numInPage: 20,
    };
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    //只要有id传过来，接请求新的数据，不要判断相等
    const { args } = nextProps;
    if (args && this.props.args && args.timestamp != this.props.args.timestamp) {
      const { dispatch } = this.props;
      const query = {
        seriesProductId: args.id,
        currentPage: 1,
        numInPage: 10000,
      };
      dispatch({
        type: 'ProductManageM/getTableData',
        payload: query,
      });

      this.setState({
        search: args.id,
      });
    }
  }
  // 点击确定
  handleOk = () => {
    const { isEdit, search } = this.state;
    const { dispatch } = this.props;
    const data = this.child.getData();
    const query = {
      listId: search,
      productCode: data.productCode,
      productName: data.productName,
      productType: data.productType,
      raisedMoney: data.raisedMoney,
      startDate: data.startDate ? data.startDate.format('YYYY-MM-DD') : '',
      endDate: data.endDate ? data.endDate.format('YYYY-MM-DD') : '',
      expectedRate: parseFloat(data.expectedRate / 100),
    };
    if (data.reward || data.reward == 0) {
      query.reward = parseFloat(data.reward / 100);
    }
    if (data.costRate || data.costRate == 0) {
      query.costRate = parseFloat(data.costRate / 100);
    }
    if (isEdit) {
      query.id = this.state.id;
    }
    if (
      // query.productCode !== undefined&&
      // query.productCode !== ''&&
      query.productName !== undefined &&
      query.productName !== '' &&
      query.productType !== undefined &&
      query.productType !== '' &&
      query.raisedMoney !== undefined &&
      query.raisedMoney !== '' &&
      query.startDate !== undefined &&
      query.startDate !== '' &&
      query.endDate !== undefined &&
      query.endDate !== '' &&
      query.expectedRate !== undefined &&
      query.expectedRate !== ''
    ) {
      const stTime = new Date(query.startDate); // 失效时间
      const edTime = new Date(query.endDate); // 生效时间
      if (stTime > edTime) {
        message.warning('到期日期不能早于起息日期');
      } else {
        dispatch({
          type: 'ProductManageM/addAndEdit',
          payload: query,
          callback: () => {
            const { dispatch, args } = this.props;
            this.child.resetDatas();
            const query = {
              seriesProductId: args.id,
              currentPage: 1,
              numInPage: 10000,
            };
            dispatch({
              type: 'ProductManageM/getTableData',
              payload: query,
            });
            this.setState({
              search: args.id,
              isVisible: false,
            });
          },
        });
      }
    } else {
      this.setState({
        isVisible: true,
      });
    }
    // this.child.resetDatas();
  };

  // 点击取消
  handleCancel = () => {
    this.setState(
      {
        isVisible: false,
      },
      () => {
        this.child.resetDatas();
      },
    );
  };

  // 新增编辑modal框
  showModal = () => {
    const { isVisible, record, isEdit } = this.state;
    const text = isEdit ? '编辑' : '新增';
    const newProps = { visible: isVisible, title: `${text}`, width: 1100 };

    return (
      <div>
        <ModalC {...newProps} onOk={this.handleOk} onCancel={this.handleCancel} className={style.ModalBody}>
          <MyModal
            onRef={(ref) => (this.child = ref)} // 父组件对本组件的引用
            isEdit={isEdit} // 修改或编辑
            defaultData={record} // 修改时回填的数据
          />
        </ModalC>
      </div>
    );
  };

  // 编辑
  editData = (record) => {
    this.setState({
      id: record.productId,
      record: record,
      isEdit: true,
      isVisible: true,
    });
  };

  // 删除
  deleteData = (record) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'ProductManageM/deleteData',
      payload: { id: record.productId },
      callback: (res) => {
        const { dispatch, args } = this.props;
        const query = {
          seriesProductId: args.id,
          currentPage: 1,
          numInPage: 10000,
        };
        dispatch({
          type: 'ProductManageM/getTableData',
          payload: query,
        });
        this.setState({
          search: args.id,
        });
      },
    });
  };

  // 新增
  handleAdd = () => {
    this.setState({
      isEdit: false,
      isVisible: true,
    });
  };

  // 改变columns的样式
  changeColumns = (columns) => {
    let data = columns;
    if (data && data.length) {
      if (data[data.length - 1].title !== '操作') {
        data.push({
          title: '操作',
          dataIndex: 'id',
          key: 'id',
          type: 'operate',
          operates: [
            {
              title: '编辑',
              onClick: (record) => this.editData(record),
            },
            {
              title: '删除',
              onClick: (record) => this.deleteData(record),
            },
          ],
        });
      }

      data.map((item) => {
        if (item.key == 'raisedMoney') {
          item.type = 'money';
        }
        if (item.key == 'expectedRate' || item.key == 'costRate' || item.key == 'reward' || item.key == 'actualRate') {
          item.type = 'rate';
        }
      });
    }
    return data;
  };
  handleChange = (page, pageSize) => {
    this.setState({
      currentPage: page,
      numInPage: pageSize,
    });
  };
  showTable = () => {
    const {
      ProductManageM: { tableData },
      loading,
    } = this.props;
    const newColumns = this.changeColumns(tableData.columns);
    const dataSource = tableData.dataSource;
    return (
      <div>
        <div style={{ marginBottom: '10px' }}>
          <PrimaryC title='新增' onClick={this.handleAdd} />
        </div>
        <TableC
          dataSource={dataSource}
          columns={newColumns}
          loading={loading}
          current={this.state.currentPage}
          pageSize={this.state.numInPage}
          onPageChange={this.handleChange}
          rowKey='productId'
        />
      </div>
    );
  };

  render() {
    const { search } = this.state;
    return (
      <div>
        {search ? <div>{this.showTable()}</div> : <NoQueryC />}
        {this.showModal()}
      </div>
    );
  }
}
